package com.sskj.trafficcontrol.util;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.HashMap;
import java.util.Map;
import java.io.*;
import java.math.BigInteger;
import java.net.*;
import java.nio.Buffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @author : zhao kuo
 * @date : 2019/2/11 19:45
 * @description :
 */
public class WeatherServiceUtil {
    public static final int cache = 10 * 1024;
    public static final boolean isWindows;
      public static final String splash;
      public static final String root;
      static {
                 if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) {
                         isWindows = true;
                         splash = "\\";
                         root="D:";
                     } else {
                         isWindows = false;
                         splash = "/";
                         root="/search";
                     }
             }
    public static String get(String  url , Map<String, String> param){

        return PureNetUtil.get(url,param);
    }

//    public static void main(String[] args) {
//        Map<String, String> param = new HashMap<>();
//
//        System.out.println(WeatherServiceUtil.get("http://wthrcdn.etouch.cn/WeatherApi",param));
//    }

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {

        System.out.println(sendHttpPost("http://wthrcdn.etouch.cn/WeatherApi?city=北京市"));

//        // TODO 请自行进行异常处理和关闭资源
//        Map<String, String> parameters = new HashMap<>();
//        parameters.put("city","北京市");
//
//
//        URL url = new URL("http://wthrcdn.etouch.cn/WeatherApi");
//        HttpURLConnection con = (HttpURLConnection) url.openConnection();
//        con.setRequestMethod("GET");
//        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
//        con.setRequestProperty("Charset", "utf-8");
//        con.setDoOutput(true);
//        con.setConnectTimeout(5000);
//        con.setReadTimeout(5000);
//        DataOutputStream out = new DataOutputStream(con.getOutputStream());
//        out.write(paramsToQueryStringUrlencoded(parameters).getBytes(Charset.forName("UTF-8")));
//
//        out.flush();
//        out.close();
//        BufferedReader in = new BufferedReader(
//                new InputStreamReader(con.getInputStream()));
//        String inputLine;
//        StringBuffer content = new StringBuffer();
//        while ((inputLine = in.readLine()) != null) {
//            content.append(inputLine);
//        }
//        in.close();
//
//        System.out.println(content.toString());

    }

    public static String paramsToQueryString(Map<String, String> params) {
        return params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
    }


    public static String paramsToQueryStringUrlencoded(Map<String, String> params) {
        return params.entrySet().stream().map(e -> {
            try {
                return e.getKey() + "=" + URLEncoder.encode(e.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                return e.getValue();
            }
        }).collect(Collectors.joining("&"));
    }

    public static String sendHttpPost(String httpUrl) throws IOException {
        // 创建HttpPost
        HttpGet httpget = new HttpGet(httpUrl);

        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpget);
        String filepath = "d://a";
                     HttpEntity entity = response.getEntity();
                     InputStream is = entity.getContent();
                     if (filepath == null)
                             filepath = getFilePath(response);
                    File file = new File(filepath);
                     file.getParentFile().mkdirs();
                     FileOutputStream fileout = new FileOutputStream(file);
                     /**
                       * 根据实际运行效果 设置缓冲区大小
                      */
                     byte[] buffer=new byte[cache];
                     int ch = 0;
                     while ((ch = is.read(buffer)) != -1) {
                             fileout.write(buffer,0,ch);
                         }
                    is.close();
                    fileout.flush();
                    fileout.close();


        return "";
    }
/**
 92      * 获取response要下载的文件的默认路径
 93      * @param response
 94      * @return
 95      */
     public static String getFilePath(HttpResponse response) {
                 String filepath = root + splash;
                String filename = getFileName(response);

                 if (filename != null) {
                         filepath += filename;
                     } else {
                         filepath += getRandomFileName();
                     }
                 return filepath;
             }

    /**
     108      * 获取response header中Content-Disposition中的filename值
     109      * @param response
     110      * @return
     111      */
     public static String getFileName(HttpResponse response) {
                 Header contentHeader = response.getFirstHeader("Content-Disposition");
                 String filename = null;
                 if (contentHeader != null) {
                         HeaderElement[] values = contentHeader.getElements();
                        if (values.length == 1) {
                                NameValuePair param = values[0].getParameterByName("filename");
                                 if (param != null) {
                                         try {
                                                 //filename = new String(param.getValue().toString().getBytes(), "utf-8");
                                                 //filename=URLDecoder.decode(param.getValue(),"utf-8");
                                                 filename = param.getValue();
                                            } catch (Exception e) {
                                                 e.printStackTrace();
                                             }
                                     }
                             }
                     }
                 return filename;
             }
     /**
 133      * 获取随机文件名
 134      * @return
 135      */
             public static String getRandomFileName() {
                 return String.valueOf(System.currentTimeMillis());
             }
     public static void outHeaders(HttpResponse response) {
                 Header[] headers = response.getAllHeaders();
                 for (int i = 0; i < headers.length; i++) {
                         System.out.println(headers[i]);
                     }
             }

}
